// pages/index.js
import React, {useEffect, useState} from 'react';
import axios from 'axios';
import {
    Button,
    Table,
    Spin,
    Alert,
    Modal,
    Form,
    Input,
    message,
    Popconfirm,
    Avatar,
    Select,
    Descriptions,
    Image,
    InputNumber,
    Flex
} from 'antd';
import http from "../services/http";
import withAuth from "./components/withAuth";

const UserPage=()=> {
    const [users, setUsers] = useState([]);
    const [workOptions, setWorkOptions] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [form] = Form.useForm();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [detailVisible, setDetailVisible] = useState(false);
    const [editForm] = Form.useForm();
    const [currentId, setCurrentId] = useState(null);//通用的当前id，用于传参
    const [detailInfo, setDetailInfo] = useState({});

    const detailItems = [
        {
            key: '1',
            label: '头像',
            children: <Image src={detailInfo.avatar} width={50} height={50}/>
        },
        {
            key: '2',
            label: '用户名',
            children: <span>{detailInfo.username}</span>
        },
        {
            key: '3',
            label: '昵称',
            children: <span>{detailInfo.nickname}</span>
        },
        {
            key: '4',
            label: '邮箱',
            children: <span>{detailInfo.email}</span>
        },
        {
            key: '5',
            label: '常驻职位',
            children: <span>{detailInfo.work_position}</span>
        },
        {
            key: '6',
            label: '工作年限',
            children: <span>{detailInfo.year}</span>
        },
    ]

    const columns = [{
        title: '用户名', dataIndex: 'username', key: 'username', render: (text) => <a>{text}</a>,
    }, {
        title: '头像', dataIndex: 'avatar', key: 'avatar', render: avatarUrl => <Avatar src={avatarUrl}/>
    }, {
        title: '昵称', dataIndex: 'nickname', key: 'nickname',
    }, {
        title: '邮箱', dataIndex: 'email', key: 'email',
    },
        {
            title: '常驻职位', dataIndex: 'work_position', key: 'work_position',
        },
        {
            title: '工作年限', dataIndex: 'year', key: 'year',
        }, {
            title: '操作', key: 'action', render: (_, record) => (<div>
                <Button onClick={() => showDetails(record)} style={{marginRight: 16}}>
                    详情
                </Button>
                <Button type="primary" style={{marginRight: 16}} onClick={() => handleEdit(record)}>修改</Button>
                <Popconfirm
                    placement="rightTop"
                    title={`确定删除 ${record.nickname} 吗?`}
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => handleDelete(record.id)}
                >
                    <Button type="primary" danger>删除</Button>
                </Popconfirm>
            </div>),
        }]

    function handleEdit(record) {
        setCurrentId(record.id);
        editForm.setFieldsValue({
            username: record.username,
            nickname: record.nickname,
            email: record.email,
            work_position: record.work_position,
            year: record.year
        });
        setEditModalVisible(true);
    }

    function showDetails(record) {
        setDetailInfo(record)
        setDetailVisible(true)
    }

    const handleEditOk = () => {
        editForm
            .validateFields()
            .then(async (values) => {
                setEditModalVisible(false);
                try {
                    const {id} = values;
                    await http.put(`/user/${currentId}`, values);
                    message.success('用户更新成功')
                    fetchUsers();
                } catch (error) {
                    console.error('更新用户失败:', error);
                    message.error('更新用户失败')
                }
            })
            .catch(info => {
            });
    };

    async function handleDelete(id) {
        await http.delete(`/user/${id}`);
        message.success('用户删除成功')
        fetchUsers();
    }

    const showModal = () => {
        setIsModalVisible(true);
    };

    const handleOk = () => {
        // const work_position = form.getFieldValue('work_position');
        // console.log('work_position:', work_position);
        form.validateFields()
            .then(async (values) => {
                setIsModalVisible(false); // 关闭模态框
                try {
                    await http.post('/user', values);
                    message.success('用户创建成功')
                    form.resetFields(); // 重置表单
                    fetchUsers();
                } catch (error) {
                    message.error('创建失败')
                }
            })
            .catch((info) => {
            });
    };


    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const fetchUsers = () => {
        setLoading(true);
        http.get('/user')
            .then(response => {
                setUsers(response.data);  // 设置用户数据
                setLoading(false);  // 更新加载状态
            })
            .catch(error => {
                console.error('Error fetching users:', error);
                setLoading(false);
            });
    };

    const selectWorkPosition = (e) => {
    }

    const getWorkPositionData = () => {
        http.get('/getWorkDicts')
            .then(response => {
                setWorkOptions(response.data.options);
            })
            .catch(error => {
                message.error(error.message)
            });
    }

    useEffect(() => {
        fetchUsers();
        getWorkPositionData();
    }, []);

    if (loading) return <Spin tip="加载中..."/>;
    if (error) return <Alert message="Error" description={error} type="error" showIcon/>;

    return (<div>
        <Button type="primary" onClick={showModal} style={{marginBottom: 16}}>
            新增用户
        </Button>
        <Table
            columns={columns}
            dataSource={users}
            bordered
            title={() => '用户列表'}
            rowKey="id"  // 假设每个用户都有唯一的 'id' 字段
        />
        <Modal
            closable={false}
            visible={detailVisible}
            footer={
                <Button onClick={() => setDetailVisible(false)}>
                    关闭
                </Button>
            }>
            <Descriptions title="用户详情" bordered items={detailItems} column={2}/>
        </Modal>

        <Modal
            title="新增用户"
            visible={isModalVisible}
            onOk={() => {
                handleOk();
            }}
            onCancel={() => {
                handleCancel();
                form.resetFields();
            }}
            okText="创建"
            cancelText="取消"
        >
            <Form
                form={form}
                layout="vertical"
                name="userForm"
                initialValues={{remember: true}}
            >
                <Form.Item
                    label="用户名"
                    name="username"
                    rules={[{required: true, message: '请输入用户名!'}]}
                >
                    <Input placeholder="请输入用户名"/>
                </Form.Item>
                <Form.Item
                    label="昵称"
                    name="nickname"
                    rules={[{required: true, message: '请输入昵称!'}]}
                >
                    <Input placeholder="请输入昵称"/>
                </Form.Item>
                <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[{type: 'email', message: '请输入有效的邮箱地址!'}]}
                >
                    <Input placeholder="请输入邮箱地址"/>
                </Form.Item>
                <Flex justify="space-between">
                    <Form.Item
                        label="职位"
                        name="work_position"
                        rules={[{required: true, message: '请选择您的职位!'}]}
                    >
                        <Select
                            placeholder="请选择您的职位"
                            style={{
                                width: 250,
                            }}
                            onChange={selectWorkPosition}
                            showSearch
                            options={workOptions}
                        />
                    </Form.Item>
                    <Form.Item
                        label="工作年限"
                        name="year"
                        rules={[{required: true, message: '请选择工作年限!'}]}
                    >
                        <InputNumber min={0} max={100} placeholder="请选择工作年限" style={{width: '150px'}}
                                     maxLength={5}/>
                    </Form.Item>
                </Flex>
            </Form>
        </Modal>

        <Modal
            title="编辑用户"
            visible={editModalVisible}
            onOk={() => {
                handleEditOk();
            }}
            onCancel={() => {
                setEditModalVisible(false);
            }}
            okText="修改"
            cancelText="取消"
        >
            <Form form={editForm} layout="vertical" name="editUserForm">
                <Form.Item name="username" label="用户名" rules={[{required: true, message: '请输入用户名!'}]}>
                    <Input/>
                </Form.Item>
                <Form.Item name="nickname" label="昵称" rules={[{required: true, message: '请输入昵称!'}]}>
                    <Input/>
                </Form.Item>
                <Form.Item name="email" label="邮箱" rules={[{type: 'email', message: '请输入有效的邮箱地址!'}]}>
                    <Input/>
                </Form.Item>
                <Flex justify="space-between">
                    <Form.Item
                        label="职位"
                        name="work_position"
                        rules={[{required: true, message: '请选择您的职位!'}]}
                    >
                        <Select
                            defaultValue={editForm.work_position}
                            style={{
                                width: 200,
                            }}
                            onChange={selectWorkPosition}
                            showSearch
                            options={workOptions}
                        />
                    </Form.Item>
                    <Form.Item
                        label="工作年限"
                        name="year"
                        rules={[{required: true, message: '请选择工作年限!'}]}
                    >
                        <InputNumber min={0} max={100} placeholder="请选择工作年限" style={{width: '150px'}}
                                     maxLength={5}/>
                    </Form.Item>
                </Flex>
            </Form>
        </Modal>


    </div>);
}

export default withAuth(UserPage, [1]); // 只允许管理员访问
